package reflection;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 需要 修改为 可以替换 内存里面的class
 */
public class MyClassLoader extends ClassLoader {
    @SuppressWarnings("deprecation")
    protected Class<?> start() throws IOException {
        byte[] clazz = loadClazz();
        return defineClass(clazz, 0, clazz.length);//todo 这一句 最关键
    }

    private byte[] loadClazz() throws IOException {
        try (FileInputStream in = new FileInputStream(new File("L:\\public\\bold\\early\\target\\classes\\reflection\\MyClassLoaderTest.class"));
             ByteArrayOutputStream byteOut = new ByteArrayOutputStream()
        ) {
            int b;
            while ((b = in.read()) != -1) {
                byteOut.write(b);
            }
            return byteOut.toByteArray();

        }
    }

    public static void main(String[] args) throws Exception {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class classz = myClassLoader.start();
        classz.getMethod("printToString").invoke(classz.newInstance());
        System.out.println(MyClassLoader.class.getClassLoader().toString());
        System.out.println(classz.getClassLoader().toString());
    }
}
